<template>
  <div class="page-container warehouse-container">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="用户产线及仓库配置" name="1"></el-tab-pane>
    </el-tabs>
    <div v-if="activeName == 1">
      
    </div>
    <div class="all-warehouse-content">
      <div class="all-row">
        <div class="all-row-box">
          <div class="title">
            <span>全部组织</span>
            <el-button type="primary" @click="handleOrgCommand({ type: 1 })" size="small">新增一级组织</el-button>
          </div>
          <div class="tree-group scrollbar">
            <el-tree :data="treeAllOrgData" ref="treeAllOrg" show-checkbox :props="{children:'children',label:'name'}" :default-checked-keys="defaultCheckeds" @check-change="treeAllOrgChange" show-checkbox node-key="id">
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <span class="tree-title">{{ node.label }}</span>
                <span @click.stop="">
                  <el-dropdown trigger="click" @command="handleOrgCommand">
                    <span class="tree-more el-icon-more"></span>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item :command="{ type: 2, data }">新增</el-dropdown-item>
                      <el-dropdown-item :command="{ type: 3, data }">编辑</el-dropdown-item>
                      <el-dropdown-item :command="{ type: 4, data }">删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </span>
              </span>
            </el-tree>
          </div>
        </div>
      </div>
      <div class="all-row">
        <div class="all-row-box">
          <div class="title">
            <span>组织下仓库</span>
            <el-button type="primary" @click="handleWarehouseCommand({ type: 1 })" size="small">添加仓库</el-button>
          </div>
          <div class="tree-group scrollbar">
            <el-checkbox-group v-model="checkedAllWarehouse">
              <div v-for="(item, index) in treeAllWarehouse" :key="index">
                <h4 class="tree-org-name" v-if="Array.isArray(item.warehouse) && item.warehouse.length!=0">{{item.name}}</h4>
                <p class="tree-checked" v-for="(v, k) in item.warehouse" :key="index+'-'+k">
                  <el-checkbox :label="v.id">{{ v.name }}</el-checkbox>
                  <span>
                    <span class="add-remove" style="margin-right:5px;" @click="handleWarehouseCommand({ type: 2 }, item)">编辑</span>
                    <span class="tree-remove" @click="handleWarehouseCommand({ type: 3 }, item)">删除</span>
                  </span>
                </p>
              </div>
            </el-checkbox-group>
          </div>
        </div>
      </div>
    </div>
    <div class="warehouse-center">
      <el-button type="primary" icon="el-icon-d-arrow-right" @click="handleAddUserCommand(1)">加入我的仓库</el-button>
    </div>
    <div class="user-warehouse-content">
      <div class="user-row">
        <div class="user-row-box">
          <div class="title title-user">我的组织</div>
          <div class="tree-group scrollbar">
            <el-tree :data="treeUserOrgData" :props="{children:'children',label:'name'}">
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <span>{{ node.label }}</span>
                <span>
                  <el-button type="text" style="font-size: red;" size="mini" @click="handleUserCommand(2, data)">
                    移除
                  </el-button>
                </span>
              </span>
            </el-tree>
          </div>
        </div>
      </div>
      <div class="user-row">
        <div class="user-row-box">
          <div class="title title-user">我的组织下仓库</div>
          <div class="tree-user-group scrollbar">
            <p class="tree-checked" v-for="(item, index) in treeUserWarehouse" :key="index">
              <span class="tree-checked-title">{{item.name}}-<span style="color:#409EFF">({{item.orgName}})</span></span>
              <span class="tree-remove" @click="handleUserCommand(3, data)">移除</span>
            </p>
          </div>
          <div class="tree-user-add"><el-button style="width:100%" type="primary" size="medium" @click="handleUserCommand(1)">确定提交</el-button></div>
        </div>
      </div>
    </div>
    <!--添加修改组织-->
    <el-dialog :title="orgTitle" :visible.sync="orgOpen" width="40%" :close-on-click-modal="false" top="1.5%">
      <div v-loading="orgLoading">
        <el-form ref="orgForm" :model="orgForm" :rules="orgRules" label-width="110px" label-position="left">
          <el-form-item label="组织名称" prop="name">
            <el-input v-model.trim="orgForm.name" placeholder="请输入目录名称" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" v-debounce-click="submitForm">确 定</el-button>
          <el-button @click="orgOpen = false">取 消</el-button>
        </div>
      </div>
    </el-dialog>
    <!--添加修改仓库-->
    <el-dialog :title="warehouseTitle" :visible.sync="warehouseOpen" width="40%">
      <div v-loading="warehouseLoading">
        <el-form ref="warehouseForm" :model="warehouseForm" :rules="warehouseRules" label-width="110px" label-position="left">
          <el-form-item label="仓库名称" prop="name">
            <el-input v-model.trim="warehouseForm.name" placeholder="请输入目录名称" />
          </el-form-item>
          <el-form-item label="组织选择" prop="contentId" v-if="addwarehouse">
            <el-cascader placeholder="组织选择" :options="data" filterable></el-cascader>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" v-debounce-click="submitForm">确 定</el-button>
          <el-button @click="warehouseOpen = false">取 消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { v4 as uuidv4 } from 'uuid';
import { mapState } from 'vuex';
import { clone, findIndex, uniqBy, find } from 'lodash';
export default {
  name: 'admin',
  data() {
    return {
      activeName:'1',
      cities: ['上海', '北京', '广州', '深圳'],
      adminTitle: '',
      orangeTitle: '',
      checkedCities: [],
      roleListVal: [],
      organizationName: '',
      roleList: [],
      searchName: '',
      searchOrgId: '',
      roleId: '',
      defaultCheckeds: [],
      tableData: [],
      adminName: '',
      editVisible: false,
      addOrEdit: 1,
      adminId: '',
      organizationData: [],
      currentPage: 1, //初始页
      pagesize: 10, //每页的数据
      total: null,
      idList: [], //选择的id数组
      tableLogin: false,
      addwarehouse: false,
      data: [],
      treeAllOrgData: [],
      treeAllWarehouse: [],
      checkedAllWarehouse: [],
      treeUserOrgData: [],
      treeUserWarehouse: [],
      orgForm: {
        name: '',//信息名称
      },
      orgRules: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" },
        ]
      },
      orgTitle: '',
      orgOpen: false,
      orgLoading: false,
      warehouseForm: {
        name: '',//信息名称
      },
      warehouseRules: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" },
        ]
      },
      warehouseTitle: '',
      warehouseOpen: false,
      warehouseLoading: false,
    };
  },
  computed: {
    ...mapState({
      userInfo: state => state.app.userInfo
    }),
  },
  mounted() {
    this.orgAjaxMethod();
    this.orgUserAjaxMethod();
  },
  methods: {
    handleLog(id) {
      this.$router.push({ path: '/journalAdmin', query: { id } });
    },
    reset() {
      this.searchName = '';
      this.currentPage = 1;
      this.roleId = '';
      this.initAjaxMethod();
    },
    mouseenter(data) {
      this.orgData.mouseenterId = data.id;
    },
    mouseleave() {
      this.orgData.mouseenterId = 0;
    },
    handleOrgCommand(command) {
      let type = command && command.type ? Number(command.type) : 0, isRemove = false, orgForm = {}, title = '', rows = command.data;
      this.orgLoading = false;
      if (type === 1) {
        title = "新增一级组织";
        orgForm.name = '';
      } else if (type === 2) {
        title = "新增组织";
        orgForm.name = '';
        orgForm.parentId = rows.id;
      } else if (type === 3) {
        title = "编辑组织";
        orgForm.name = rows && rows.name ? rows.name : '';
        orgForm.id = rows.id;
      } else {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.orgRemove(rows.id);
        });
        isRemove = true;
      }
      if (isRemove) return;
      console.log('orgForm', orgForm);
      this.orgTitle = title;
      this.orgForm = orgForm;
      this.orgOpen = true;
      this.$nextTick(() => {
        this.$refs['orgFrom'].clearValidate();
      });

    },
    handleWarehouseCommand(command) {
      let type = command && command.type ? Number(command.type) : 0, isRemove = false, warehouseForm = {}, title = '', rows = command.data;
      this.orgLoading = false;
      this.addwarehouse = false;
      if (type === 1) {
        title = "新增仓库";
        warehouseForm.name = '';
        this.addwarehouse = true;
      } else if (type === 2) {
        title = "编辑仓库";
        warehouseForm.name = '';
        warehouseForm.parentId = rows.id;
      } else if (type === 3) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.warehouseRemove(rows.id);
        });
        isRemove = true;
      }
      if (isRemove) return;
      this.warehouseTitle = title;
      this.warehouseForm = warehouseForm;
      this.warehouseOpen = true;
      this.$nextTick(() => {
        this.$refs['warehouseForm'].clearValidate();
      });
    },
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.dialogLoading = true;
          if (isString(this.form.id)) {
            this.$http.put(this.$API.WORK_CALALOG_BATH + '/' + this.form.id, this.form, {
              headers: { 'Content-Type': 'application/json' }
            }).then((response) => {
              this.$message.success('修改成功');
              this.open = false;
              this.dialogLoading = false;
              this.initAjaxMethod();
            });
          } else {
            let addParmes = this.form;
            addParmes.id = uuidv4();
            this.$http.post(this.$API.WORK_CALALOG_BATH, addParmes, {
              headers: { 'Content-Type': 'application/json' }
            }).then((response) => {
              this.$message.success('添加成功');
              this.open = false;
              this.dialogLoading = false;
              this.initAjaxMethod();
            });
          }

        }
      });
    },
    orgRemove() {
      const loading = this.$loading({ text: '加载中...' });
      this.$http
        .post(this.$API.ORGANIZATION, {})
        .then(res => {
          loading.close();
          console.log('组织列表', res);
          if (res.code == 1) {
            this.organizationData = res.data;
            this.orgData.showOrgTree = false;
            this.$nextTick(() => {
              this.orgData.showOrgTree = true;
            });
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch(err => {
          loading.close();
        });
    },
    warehouseRemove() {
      const loading = this.$loading({ text: '加载中...' });
      this.$http
        .post(this.$API.ORGANIZATION, {})
        .then(res => {
          loading.close();
          console.log('组织列表', res);
          if (res.code == 1) {
            this.organizationData = res.data;
            this.orgData.showOrgTree = false;
            this.$nextTick(() => {
              this.orgData.showOrgTree = true;
            });
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch(err => {
          loading.close();
        });
    },
    submitWorkForm() {
      this.$refs["workform"].validate((valid) => {
        if (valid) {
          this.dialogworkLoading = true;
          if (isString(this.formwork.id)) {
            this.$http.put(this.$API.WORK_TASK + '/' + this.form.id, this.formwork, {
              headers: { 'Content-Type': 'application/json' }
            }).then((response) => {
              this.$message.success('修改成功');
              this.openwork = false;
              this.dialogworkLoading = false;
              this.initAjaxMethod();
            });
          } else {
            let addParmes = this.formwork;
            addParmes.id = uuidv4();
            this.$http.post(this.$API.WORK_TASK, addParmes, {
              headers: { 'Content-Type': 'application/json' }
            }).then((response) => {
              this.$message.success('添加成功');
              this.openwork = false;
              this.dialogworkLoading = false;
              this.initAjaxMethod();
            });
          }

        }
      });
    },
    handleAddUserCommand() {
      if (this.checkedAllWarehouse.length == 0) return this.$message.error('请选择仓库');
      let treeUserOrgData = clone(this.treeUserOrgData);
      let treeUserWarehouse = clone(this.treeUserWarehouse);
      this.treeAllWarehouse.forEach(item => {
        if (item.warehouse && Array.isArray(item.warehouse)) {
          let isAdd = false;
          item.warehouse.forEach(val => {
            let cIndex = findIndex(this.checkedAllWarehouse, o => o === val.id);
            if (cIndex >= 0) {
              isAdd = true;
              treeUserWarehouse.push({ name: val.name, id: val.id,orgId:val.orgId,orgName:val.orgName})
            }
          })
          if (isAdd) {
            treeUserOrgData.push({ name: item.name, id: item.id })
          }
        }

      })
      this.treeUserWarehouse = uniqBy(treeUserWarehouse, o => o.id);
      this.treeUserOrgData = uniqBy(treeUserOrgData, o => o.id);
    },
    handleUserCommand(flag, rows) {
      let title = '';
      if (flag === 1) {
        title = "确定将已勾选仓库添加到我的仓库中？";
      } else if (flag === 2) {
        title = "确定移除组织及组织下面的所有仓库？";
      } else if (flag === 3) {
        title = "确定移除所选仓库？";
      }
      this.$confirm(title, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (flag === 1) {
          const loading = this.$loading({ text: '加载中...' });
          this.$http.post(this.$API.SET_USER_ORG+'?id='+this.userInfo.id, this.treeUserOrgData.map(o=>o.id)).then((res) => {
            this.$http.post(this.$API.SET_USER_WARES+'?id='+this.userInfo.id, this.treeUserWarehouse.map(o=>o.id)).then((res) => {
                this.$message.success('操作成功');
                loading.close();
              }).catch(err => {
                loading.close();
              });
          }).catch(err => {
            loading.close();
          });
        }else if(flag === 2){
          let userWarehouse=[];
          this.treeUserWarehouse.forEach((item)=>{
            if(item.orgId != rows.id){
              userWarehouse.push(item)
            }
          })
          let oIndex=findIndex(this.treeUserOrgData,o=>o.id === rows.id);
          if(oIndex>=0)this.treeUserOrgData.splice(oIndex,1);
          this.treeUserWarehouse=userWarehouse;
        }else if(flag === 3){
          let oIndex=findIndex(this.treeUserWarehouse,o=>o.id === rows.id);
          if(oIndex>=0)this.treeUserWarehouse.splice(oIndex,1);
        }
      });
    },
    //组织架构
    orgAjaxMethod() {
      const loading = this.$loading({ text: '加载中...' });
      this.$http
        .get(this.$API.ORGANIZATION, { companyId: this.userInfo.company.id })
        .then(res => {
          loading.close();
          this.treeAllOrgData = Array.isArray(res.data) ? res.data : [];
        })
        .catch(err => {
          loading.close();
        });
    },
    treeAllOrgChange(e) {
      let nodes = this.$refs.treeAllOrg.getCheckedNodes(), keys = [];
      nodes.forEach(item => {
        if (!item.children || item.children.length === 0) {
          keys.push({ id: item.id, name: item.name,warehouse:[]})
        }
      })
      if (keys.length > 0) {
        this.warehouseAjaxMethod(keys)
      }
    },
    //仓库
    warehouseAjaxMethod(keys) {
      const loading = this.$loading({ text: '加载中...' });
      this.$http
        .get(this.$API.GET_WAREHOUSE+'?'+keys.map(o=>'orgIds='+o.id).join('&'))
        .then(res => {
          loading.close();
          let warehouse = Array.isArray(res.data) ? res.data : [];
          keys.forEach(item=>{
            warehouse.forEach(val=>{
              if(val.organization.id === item.id){ 
                item.warehouse.push({id:val.id,name:val.name,orgId:(val.organization?val.organization.id:''),orgName:(val.organization?val.organization.name:'')})
              }
            })
          })
          this.treeAllWarehouse = keys;
        })
        .catch(err => {
          loading.close();
        });
    },
    orgUserAjaxMethod() {
      const loading = this.$loading({ text: '加载中...' });
      this.$http
        .get(this.$API.GET_USER_WARE, {userId:this.userInfo.id})
        .then(res => {
          loading.close();
          let list=Array.isArray(res.data)?res.data:[],treeUserWarehouse=[],treeUserOrgData=[];
          if(list.length === 0)return;
          list.forEach(val => {
            treeUserWarehouse.push({ name: val.name, id: val.id,orgId:val.organization?val.organization.id:'',orgName:val.organization?val.organization.name:''})
            treeUserOrgData.push({ name: val.organization?val.organization.name:'', id: val.organization?val.organization.id:'' })
          })
          this.treeUserWarehouse = uniqBy(treeUserWarehouse, o => o.id);
          this.treeUserOrgData = uniqBy(treeUserOrgData, o => o.id);
          this.defaultCheckeds=this.treeUserOrgData.map(item=>item.id);
          this.checkedAllWarehouse=this.treeUserWarehouse.map(item=>item.id);
          let keys=[];
          this.treeUserOrgData.forEach(item=>{
            keys.push({ id: item.id, name: item.name,warehouse:[]})
          })
          this.warehouseAjaxMethod(keys);
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },
  }
};
</script>

<style lang="less">
.warehouse-container {
  // display: flex;
  padding: 10px;
  height: 100%;

  .all-warehouse-content {
    width: 45%;
    height: 100%;
    border: 1px solid #eee;
    border-radius: 6px;
    display: flex;

    .all-row {
      width: 50%;
      padding: 10px;
      height: 100%;

      .all-row-box {
        height: 100%;
        border: 1px solid #eee;
      }
    }
  }

  .warehouse-center {
    width: 10%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .title {
    font-size: 14px;
    padding: 10px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    span {
      font-weight: bold;
    }
  }

  .tree-group {
    height: 86vh;
  }
  .tree-user-group{
    height: 82vh;
    position: relative;
  }
  .tree-user-add{
    display: flex;
    align-items: center;
    justify-content: center;
    padding-top:10px;
  }

  .user-warehouse-content {
    width: 45%;
    height: 100%;
    border: 1px solid #eee;
    border-radius: 6px;
    display: flex;

    .user-row {
      width: 50%;
      padding: 10px;
      height: 100%;

      .user-row-box {
        height: 100%;
        border: 1px solid #eee;
      }
    }
  }

  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }

  .tree-checked {
    padding: 3px 20px;
    display: flex;
    justify-content: space-between;
    font-size: 14px;
    color:#333;
  }
  .tree-org-name {
    font-size: 13px;
    padding: 5px 10px;
    margin: 0;
  }

  .tree-remove {
    font-size: 12px;
    color: red;
  }

  .add-remove {
    font-size: 12px;
    color: #66b1ff;
  }

  .title-user {
    font-weight: bold;
    justify-content: center;
  }
  .tree-checked-title{
    max-width: 85%;
  }
  .el-checkbox{
    display: flex;
    align-items: center;
  }
  .el-checkbox__label{
    max-width: 180px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
</style>